package com.powernode.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.domain.Prod;
import com.powernode.domain.ProdTagReference;
import com.powernode.domain.Sku;
import com.powernode.mapper.ProdMapper;
import com.powernode.service.ProdService;
import com.powernode.service.ProdTagReferenceService;
import com.powernode.service.SkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

@Service
public class ProdServiceImpl extends ServiceImpl<ProdMapper, Prod> implements ProdService{

    @Autowired
    private ProdTagReferenceService prodTagReferenceService;

    @Autowired
    private SkuService skuService;

    /**
     * 新增商品
     *
     * @param prod
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveProd(Prod prod) {
        // 首先新增商品

        prod.setCreateTime(new Date());
        prod.setUpdateTime(new Date());
        prod.setShopId(1L);
        // 设置销量
        prod.setSoldNum(0);
        prod.setVersion(0);
        Prod.DeliveryModeVo deliveryModeVo = prod.getDeliveryModeVo();
        prod.setDeliveryMode(JSONObject.toJSONString(deliveryModeVo));

        boolean save = this.save(prod);

        if (!save){
            return save;
        }
        Long prodId = prod.getProdId();
        // 保存商品分组和商品的关系
        List<Long> tagList = prod.getTagList();
        if (tagList != null && tagList.size() > 0){
            List<ProdTagReference> prodTagReferenceList = new ArrayList<>();
            for (Long tagId : tagList) {
                ProdTagReference prodTagReference = new ProdTagReference();
                prodTagReference.setCreateTime(new Date());
                prodTagReference.setProdId(prodId);
                prodTagReference.setTagId(tagId);
                prodTagReference.setStatus(prod.getStatus());
                prodTagReference.setShopId(prod.getShopId());
                prodTagReferenceList.add(prodTagReference);
            }
            prodTagReferenceService.saveBatch(prodTagReferenceList);
        }

        // 保存商品和sku的关系
        List<Sku> skuList = prod.getSkuList();
        if (skuList != null && skuList.size() > 0){
            for (Sku sku : skuList) {
                sku.setProdId(prodId);
                sku.setCreateTime(new Date());
                sku.setUpdateTime(new Date());
                sku.setVersion(0);
                sku.setActualStocks(sku.getStocks());
            }
            skuService.saveBatch(skuList);
        }


        return save;
    }

    /**
     * 根据id查询商品详情
     *
     * @param prodId
     * @return
     */
    @Override
    public Prod getProdById(Long prodId) {

        // 首先查询对应商品信息
        Prod prod = getById(prodId);
        if (prod == null){
            return null;
        }

        // 查询对应的分组信息

        List<ProdTagReference> list = prodTagReferenceService.list(
                new LambdaQueryWrapper<ProdTagReference>()
                        .eq(ProdTagReference::getProdId, prodId)
        );

        List<Long> tagList = list.stream().map(ProdTagReference::getTagId).collect(Collectors.toList());

        prod.setTagList(tagList);

        // 查询商品对应的sku信息
        List<Sku> skuList = skuService.list(
                new LambdaQueryWrapper<Sku>()
                        .eq(Sku::getProdId, prodId)
        );

        prod.setSkuList(skuList);

        return prod;
    }

    /**
     * 修改商品
     *
     * @param prod
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean modifyProd(Prod prod) {
        prod.setUpdateTime(new Date());

        Prod.DeliveryModeVo deliveryModeVo = prod.getDeliveryModeVo();
        prod.setDeliveryMode(JSONObject.toJSONString(deliveryModeVo));

        Long prodId = prod.getProdId();
        // 首先删除对应的分组关系,然后插入新的分组关系
        boolean remove = prodTagReferenceService.remove(
                new LambdaQueryWrapper<ProdTagReference>()
                        .eq(ProdTagReference::getProdId, prodId)
        );

        List<Long> tagList = prod.getTagList();
        if (tagList != null && tagList.size() > 0){
            List<ProdTagReference> prodTagReferenceList = new ArrayList<>();
            for (Long tagId : tagList) {
                ProdTagReference prodTagReference = new ProdTagReference();
                prodTagReference.setCreateTime(new Date());
                prodTagReference.setProdId(prodId);
                prodTagReference.setTagId(tagId);
                prodTagReference.setStatus(prod.getStatus());
                prodTagReference.setShopId(prod.getShopId());
                prodTagReferenceList.add(prodTagReference);
            }
            prodTagReferenceService.saveBatch(prodTagReferenceList);
        }

        // 删除sku信息,然后插入新的sku信息
        skuService.remove(
                new LambdaQueryWrapper<Sku>()
                        .eq(Sku::getProdId, prodId)
        );

        // 保存商品和sku的关系
        List<Sku> skuList = prod.getSkuList();
        if (skuList != null && skuList.size() > 0){
            for (Sku sku : skuList) {
                sku.setProdId(prodId);
                sku.setCreateTime(new Date());
                sku.setUpdateTime(new Date());
                sku.setVersion(0);
                sku.setActualStocks(sku.getStocks());
            }
            skuService.saveBatch(skuList);
        }


        // 修改商品信息
        boolean b = this.updateById(prod);

        return b;
    }

    /**
     * 删除商品&批量删除商品
     *
     * @param prodIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeProdByIds(List<Long> prodIds) {
        // 删除商品标签关联信息
        AtomicBoolean isSuccess = new AtomicBoolean(false);
        prodIds.forEach(prodId -> {
            // 删除分组关联信息
            prodTagReferenceService.remove(
                    new LambdaQueryWrapper<ProdTagReference>()
                            .eq(ProdTagReference::getProdId, prodId)
            );
            // 删除sku信息
            skuService.remove(
                    new LambdaQueryWrapper<Sku>()
                            .eq(Sku::getProdId, prodId)
                    );
            // 删除商品信息
            isSuccess.set(this.removeById(prodId));
        });

        return isSuccess.get();
    }
}
